<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12" v-if="!contentflag">
            <a-form-model-item label="关联费用报销单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relReimbursementBillId">
              <select-finance-reimbursement-bill-input :disabled="formDisabled || !teamId" :teamId="teamId" :applicant="applicant" v-model="model.relReimbursementBillId" @back="getBillInfo"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="contentflag">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <a-input
                v-if="formDisabled"
                readOnly
                @click.prevent="goProjectDetail(model)"
                v-model="model.projectName"
                style="color: #1890FF; cursor: pointer;"
                placeholder="请选择项目"></a-input>
              <select-project-input
                :queryParamType="'1'"
                v-model="model.projectId"
                :teamId="teamId"
                :companyId="applicant"
                placeholder="请选择项目"
                :disabled="formDisabled || !teamId "
                @input="selectProject" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="contentflag">
            <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectCode">
              <a-input disabled v-model="model.projectCode" placeholder="请输入项目编号" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!--迭代10财务优化 TASK#3400 付款申请单-子表删除“情况说明”，“项目承接人””-->
          <!-- <a-col :span="12" v-if="contentflag">
            <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectUndertaker">
              <select-user-by-dep :disabled=formDisabled  :multi="false"
                  v-model="model.projectUndertaker" disabled></select-user-by-dep>
            </a-form-model-item>
          </a-col> -->
          <!--迭代6财务优化”-->
          <a-col :span="12" v-if="contentflag">
            <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectYear">
              <j-dict-select-tag
                type="list"
                v-model="model.projectYear"
                dictCode="yjgsnd"
                placeholder="请选择业绩归属年度"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12" v-if="contentflag">
            <a-form-model-item label="费用所属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamYear">
              <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.teamYear" dictCode="tdnd_type" placeholder="请选择费用所属年度" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
              <select-team-input
                  :disabled=formDisabled
                  v-model="model.teamId" :tdlx="3" disabled/>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="12" v-if="contentflag">
            <a-form-model-item label="合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractType">
              <j-dict-select-tag
                :disabled="formDisabled"
                type="list"
                v-model="model.contractType"
                dictCode="contract_type"
                placeholder="请选择合同类型"
                @input="selectContract"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="contentflag && model.contractType">
            <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractId">
              <select-purchase-contract-input
                v-if="model.contractType=='2'"
                :disabled="formDisabled || !teamId || !applicant"
                :teamId="model.projectId?null:teamId"
                :demandCompanName="model.projectId?null:applicant"
                v-model="model.contractId"
                :projectId="model.projectId"
                style="width: 100%"
                placeholder="请选择采购合同" />
              <select-contract-manager-input
                showName="1"
                v-if="model.contractType=='1'"
                :allList="!model.projectId?true:false"
                :muitFlag="true"
                :disabled="formDisabled || !teamId || !applicant"
                :jytd="model.projectId?null:teamId"
                :signUnit="model.projectId?null:applicant"
                v-model="model.contractId"
                htlx="2"
                :projectId="model.projectId" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12"  v-if="!contentflag">
            <a-form-model-item label="费用类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reimbursementFeeType">
              <a-input :disabled=formDisabled v-model="model.reimbursementFeeType" placeholder="请输入费用报销类别" disabled></a-input>
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :span="12"  v-if="contentflag">
            <a-form-model-item label="费用类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectFeeType">
              <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.projectFeeType" dictCode="payment_expense_category" placeholder="请选择项目费用类别" />
            </a-form-model-item>
          </a-col> -->
          <!--迭代10财务优化 TASK#3400 付款申请单-子表删除“情况说明”，“项目承接人””-->
          <!-- <a-col :span="12"  v-if="contentflag">
            <a-form-model-item label="情况说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input :disabled="formDisabled || !contentflag"  @change="inputAmount"  v-model="model.remark" placeholder="请输入情况说明" style="width: 100%" :max-length="500"/>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="12" v-if="!contentflag">
            <a-form-model-item label="应付（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payableAmount">
              <a-input-number
                disabled
                :max="99999999"
                :min="0"
                :precision="2"
                @change="inputAmount"
                v-model="model.payableAmount"
                placeholder="请输入应付"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="!contentflag">
            <a-form-model-item label="已付（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paidAmount">
              <a-input-number
                disabled
                :max="99999999"
                :min="0"
                :precision="2"
                @change="inputAmount"
                v-model="model.paidAmount"
                placeholder="请输入已付"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="!contentflag">
            <a-form-model-item label="扣款（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deductionAmount">
              <a-input-number
                disabled
                :max="99999999"
                :min="0"
                :precision="2"
                @change="inputAmount"
                v-model="model.deductionAmount"
                placeholder="请输入扣款"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="!contentflag">
            <a-form-model-item label="本次扣款（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currentDeductionAmount">
              <a-input-number
                :disabled="formDisabled"
                :max="model.payableAmount?model.payableAmount:9999999"
                :min="0"
                :precision="2"
                @change="inputAmount"
                v-model="model.currentDeductionAmount"
                placeholder="请输入本次扣款"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="!contentflag">
            <a-form-model-item label="本次支付（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currentPaidAmount">
              <a-input-number
                :disabled="formDisabled"
                :max="model.payableAmount?model.payableAmount:9999999"
                :min="0"
                :precision="2"
                @change="inputAmount"
                v-model="model.currentPaidAmount"
                placeholder="请输入本次支付"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="contentflag">
            <a-form-model-item label="本次预付金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currentPaidAmount">
              <a-input-number
                :disabled="formDisabled"
                :max="model.payableAmount?model.payableAmount:9999999"
                :min="0"
                :precision="2"
                @change="inputAmount"
                v-model="model.currentPaidAmount"
                placeholder="请输入预付金额"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="!contentflag">
            <a-form-model-item label="未付款（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unpaidAmount">
              <a-input-number
                :max="99999999"
                v-model="model.unpaidAmount"
                :precision="2"
                placeholder="请输入未付款"
                style="width: 100%"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-input-number :disabled="formDisabled" :hidden="true" v-model="model.onChargedAmount" style="width: 100%" />
          <a-input-number :disabled="formDisabled" :hidden="true" v-model="model.unChargedAmount" style="width: 100%" />
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import SelectContractManagerInput from '@/views/scy/components/SelectContractManagerInput'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
  import SelectFinanceReimbursementBillInput from '@/views/scy/components/SelectFinanceReimbursementBillInput'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectPurchaseContractInput from '@/views/scy/components/SelectPurchaseContractInput'

  export default {
    name: 'ErpFinancePaymentSlipFeeDetailForm',
    components: {
      SelectUserByDep,
      SelectContractManagerInput,
      SelectProjectInput,
      SelectTeamInput,
      SelectPersonInput,
      SelectFinanceReimbursementBillInput,
      SelectPurchaseContractInput
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      // 费用所属团队
      teamId: {
        type: String,
        default: null,
        required: false
      },
      applicant: {
        type: String,
        default: null,
        required: false
      }
    },
    data () {
      return {
        model: {
          currentDeductionAmount: 0
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        projectType: '2',
        confirmLoading: false,
        validatorRules: {
          // projectId: [
          //     { required: true, message: '请输入项目编号!'},
          // ],
          // contractId: [
          //     { required: true, message: '请输入合同编号!'},
          // ],
          // projectFeeType: [
          //     { required: true, message: '请输入项目费用类别!'},
          // ],
          // TASK#3398 付款申请单-去除子表中“业绩所属年度”、“费用所属年度”、“费用所属团队”
          // teamYear: [
          //     { required: true, message: '请输入费用所属年度!'},
          // ],
          // teamId: [
          //     { required: true, message: '请输入费用所属团队!'},
          // ],
          // teamLeader: [
          //     { required: true, message: '请输入团队领导!'},
          // ],
          payableAmount: [
            { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ],
          paidAmount: [
              { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ],
          deductionAmount: [
            { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ],
          currentDeductionAmount: [
              { required: false, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ],
          currentPaidAmount: [
              { required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ],
          unpaidAmount: [
            { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '未付款金额不正确!' }
          ],
          relReimbursementBillId: [
              { required: true, message: '请输入关联费用报销单!' }
          ],
          reimbursementFeeType: [
              { required: true, message: '请输入费用报销类别!' }
          ]
          // <!--迭代10财务优化 TASK#3400 付款申请单-子表删除“情况说明”，“项目承接人””-->
          // remark: [
          //     { required: true, message: '请输入情况说明!'},
          // ],
        },
        url: {
          queryBillByContractId: '/api/erp/finance/payment/erpFinancePaymentSlip/queryBillByContractId',
          queryReimbursementById: '/api/erp/finance/reimbursement/erpFinanceReimbursementBill/queryById',
          queryBillByBillId: '/api/erp/finance/payment/erpFinancePaymentSlipFeeDetail/queryBillByBillId',
          add: '/api/erp/finance/payment/erpFinancePaymentSlipFeeDetail/add',
          edit: '/api/erp/finance/payment/erpFinancePaymentSlipFeeDetail/edit',
          queryById: '/api/erp/finance/payment/erpFinancePaymentSlipFeeDetail/queryById'
        },
        contentflag: false,
        dictOptions: {}
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 加载数据字典信息
      this.initDictConfig();
    },
    methods: {
      // 加载字典
      async initDictConfig() {
        initDictOptions('sys_category,name,code').then(async(res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'big_category_salary', res.result)
            this.$set(this.dictOptions, 'small_category_salary', res.result)
            this.$set(this.dictOptions, 'big_category_daily', res.result)
            this.$set(this.dictOptions, 'small_category_daily', res.result)
          }
        })
        initDictOptions('erp_material_category,category_name,id').then(async(res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'big_category_purchasey', res.result)
            this.$set(this.dictOptions, 'small_category_purchasey', res.result)
          }
        })
      },
      // 获得费用报销单信息
      getBillInfo(data) {
        console.log(data);
        if (data) {
          let paidAmount = 0;
          // 加载数据字典信息
          // this.initDictConfig();
          // 处理费用类别
          // getAction(this.url.queryReimbursementById, {'id':data[0].id}).then((res) => {
          //   if (res.success) {
          //     let result=res.result;
          //     console.log(result);
          //     if(result){
          //       if(result.feeCategory=='0'){//福利类
          //        // this.$set(this.model,'teamId',result.teamId);
          //        // this.$set(this.model,'reimbursementFeeType',filterMultiDictText(this.dictOptions['big_category_salary'], result.salaryFeeInfo.bigCategory + '')+'-'+filterMultiDictText(this.dictOptions['small_category_salary'], result.salaryFeeInfo.smallCategory + ''));
          //       }else if(result.feeCategory=='1'){//采购类
          //        // this.$set(this.model,'teamId',result.teamId);
          //        // this.$set(this.model,'reimbursementFeeType',filterMultiDictText(this.dictOptions['big_category_purchasey'], result.purchaseyFeeInfo.bigCategory + '')+'-'+filterMultiDictText(this.dictOptions['small_category_purchasey'], result.purchaseyFeeInfo.smallCategory + ''));
          //       }else if(result.feeCategory=='2'){//费用类
          //           // if(result.dailyFeeInfoList.length>1){
          //           //   this.$message.error('所选择的费用报销单费用类报销大于1条');
          //           //   this.$set(this.model,'relReimbursementBillId','');
          //           //   return;
          //           // }
          //        // this.$set(this.model,'teamId',result.teamId);
          //        // this.$set(this.model,'reimbursementFeeType',filterMultiDictText(this.dictOptions['big_category_daily'], result.dailyFeeInfoList[0].bigCategory + '')+'-'+filterMultiDictText(this.dictOptions['small_category_daily'], result.dailyFeeInfoList[0].smallCategory + ''));
          //       }
          //     }
          //   }
          // })
          paidAmount = data[0].totalPayAmount + data[0].chargedAmount;
          this.$set(this.model, 'deductionAmount', data[0].deductionAmount);
          this.$set(this.model, 'paidAmount', paidAmount.toFixed(2));
          this.$set(this.model, 'payableAmount', data[0].reimbursementAmount);
          if (this.model.currentPaidAmount) {
            this.$set(this.model, 'currentPaidAmount', 0);
            this.$set(this.model, 'unpaidAmount', 0);
          }
          if (this.model.currentDeductionAmount) {
            this.$set(this.model, 'currentDeductionAmount', 0);
            this.$set(this.model, 'unpaidAmount', 0);
          }
          // getAction(this.url.queryBillByBillId, {'billId':data[0].id}).then((res) => {
          //   if (res.success) {
          //     let data = res.result
          //     this.$set(this.model,"deductionAmount",data.deductionAmount);
          //     if(data.payAmount>0){
          //       paidAmount=data.payAmount;
          //     }else{
          //       paidAmount=(paidAmount+data.payAmount).toFixed(2);
          //     }
          //     this.$set(this.model,'paidAmount',paidAmount);
          //   }
          // })
        }
      },
      // 切换合同类型
      selectContract(data) {
        if (data) {
          if (this.model.contractId) {
            this.$set(this.model, 'contractId', null);
          }
        }
      },
      // 输入金额
      inputAmount() {
        console.log('data{}', this.model.payableAmount, this.model.paidAmount, this.model.deductionAmount, this.model.currentDeductionAmount, this.model.currentPaidAmount);
        let unpaidAmount = (this.model.payableAmount - this.model.paidAmount - this.model.deductionAmount - this.model.currentDeductionAmount - this.model.currentPaidAmount).toFixed(2);
        if ((!!this.model.payableAmount || this.model.payableAmount == 0) && (!!this.model.paidAmount || this.model.paidAmount == 0) && (!!this.model.deductionAmount || this.model.deductionAmount == 0) && (!!this.model.currentDeductionAmount || this.model.currentDeductionAmount == 0) && (!!this.model.currentPaidAmount || this.model.currentPaidAmount == 0)) {
            if (unpaidAmount == -0.00) {
              unpaidAmount = 0;
            }
            this.$set(this.model, 'unpaidAmount', unpaidAmount);
        }
        this.$set(this.model, 'onChargedAmount', 0);
        this.$set(this.model, 'unChargedAmount', this.model.currentPaidAmount);
      },
      // 获取合同信息
      // getContractInfo(data){
      //   if(data){
      //    this.model.payableAmount=data[0].bchte;
      //    getAction(this.url.queryBillByContractId, {'contractId':data[0].id}).then((res) => {
      //       if (res.success) {
      //         let resData = res.result
      //         this.$set(this.model,"deductionAmount",resData.deductionAmount);
      //         this.$set(this.model,'paidAmount',resData.paidAmount);
      //       }
      //     })
      //   }
      // },
      // 获取项目信息
      selectProject(data) {
        this.$set(this.model, 'contractId', null);
        if (data) {
          // 如果删除项目，需要重置合同
          if (data.choseObj.length == 0) {
            this.$set(this.model, 'contractId', null);
            this.model.projectCode = null
            this.model.projectYear = null
          } else {
            this.model.projectCode = data.choseObj[0].finalNo
            this.model.projectYear = data.choseObj[0].year
          }
          if (this.model.contractId) {
            this.$set(this.model, 'contractId', null);
          }
          // <!--迭代10财务优化 TASK#3400 付款申请单-子表删除“情况说明”，“项目承接人””-->
          // this.model.projectUndertaker=data.choseObj[0].undertaker;
          // 付款申请单-去除子表中“业绩所属年度”、“费用所属年度”、“费用所属团队”
          // this.model.projectYear=data.choseObj[0].year;
          // this.model.teamId=data.choseObj[0].teamName;
          // if(data.cutStatus!="2"){
          //   this.$message.error('请选择立项项目！');
          //   this.$set(this.model,'projectId',null);
          //   this.$set(this.model,'teamLeader','');
          //   this.$set(this.model,'teamYear',null)
          //   this.$set(this.model,'teamId','')
          //   return ;
          // }else{
          //   this.model.teamLeader=data.choseObj[0].undertaker;
          //   this.model.teamYear=data.choseObj[0].year;
          //   this.model.teamId=data.choseObj[0].teamName;
          // }
        }
      },
      add (flag) {
        this.edit(this.modelDefault);
        this.contentflag = flag
        if (flag) {
          this.$refs.form.clearValidate('relReimbursementBillId');
          this.$refs.form.clearValidate('reimbursementFeeType');
          this.validatorRules.relReimbursementBillId = []
          this.validatorRules.reimbursementFeeType = []
        } else {
          this.$refs.form.clearValidate('projectId');
          this.$refs.form.clearValidate('contractId');
          this.$refs.form.clearValidate('projectFeeType');
          // this.$refs.form.clearValidate('teamYear');
          // this.$refs.form.clearValidate('teamId');
          this.$refs.form.clearValidate('teamLeader');
          this.$refs.form.clearValidate('reimbursementFeeType');
          this.validatorRules.projectId = []
          this.validatorRules.contractId = []
          this.validatorRules.projectFeeType = []
          this.validatorRules.reimbursementFeeType = []
          // this.validatorRules.teamId = []
          this.validatorRules.teamLeader = []
          // this.validatorRules.teamYear = []
        }
      },
      edit (record, flag) {
        this.$refs['form'].clearValidate();
        Object.assign(this.$data, this.$options.data())
        // this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.contentflag = flag
        if (flag) {
          this.$refs.form.clearValidate('relReimbursementBillId');
          this.$refs.form.clearValidate('reimbursementFeeType');
          this.validatorRules.relReimbursementBillId = []
          this.validatorRules.reimbursementFeeType = []
        }
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            if (!this.model.id) {
              this.model.id = parseInt(Math.random() * 1000000000000);
            }
            this.$emit('ok', this.model);
          }
        })
      }
    }
  }
</script>
